//
//  LKCustomerAppointmentViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/5/4.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKCustomerAppointmentViewController.h"
#import "LKWorkListDetailCell.h"
#import "LKWorkOrderListDetailCell.h"
#import "LKOrderEditTopView.h"
#import "LKWriteAppointMessageViewController.h"
#import "LKChooseProductDetailViewController.h"
@interface LKCustomerAppointmentViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)LKBaseTableview *tableView;
@property(nonatomic,strong)NSMutableArray *titlesArray;
@property(nonatomic,strong)NSMutableArray *idsArray;

@end

@implementation LKCustomerAppointmentViewController

-(LKBaseTableview *)tableView{
    if (!_tableView) {
        _tableView = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, 10 + NAVIGATION_BAR_HEIGHT, WIDTH, HEIGHT - (NAVIGATION_BAR_HEIGHT  - 10)) style:UITableViewStyleGrouped registercellClasss:@[@"LKWorkOrderListDetailCell"]];
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        _tableView.emptyDataSetDelegate = self;
//        _tableView.emptyDataSetSource = self;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    [self getCurrentCustomerInformation];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTableViewData:) name:@"appointmentProductNotice" object:nil];
//    self.tableView.estimatedRowHeight = 200;
    // Do any additional setup after loading the view.
}
-(void)reloadTableViewData:(NSNotification *)notice{
    [self.titlesArray removeAllObjects];
    [self.idsArray removeAllObjects];
    [self getCurrentCustomerInformation];
}
-(void)setNavgationBackBtn{
    WS(weakSelf)
    [super setNavgationBackBtn];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [btn setTitle:@"预约" forState:UIControlStateNormal];
    [btn setTitleColor:blueDefault forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
//        LKWriteAppointMessageViewController *vc = [[LKWriteAppointMessageViewController alloc] init];
//        vc.model = weakSelf.model;
       LKChooseProductDetailViewController *vc = [[LKChooseProductDetailViewController alloc] init];
        vc.customerModel = weakSelf.model;
        vc.IsAppoint = YES;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    self.navigationItem.title = @"客户预约信息";
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.titlesArray.count ;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSDictionary *dic = self.titlesArray[section];
    NSArray *contentArra = [[dic allValues] firstObject];
    return contentArra.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = self.titlesArray[indexPath.section];
    NSArray *contentArra = [[dic allValues] firstObject];
    LKWorkOrderListDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKWorkOrderListDetailCell"];
    cell.arrowBtn.hidden = YES;
    cell.lineView.hidden = YES;
    if (indexPath.row == 0) {
        cell.lineView.hidden = NO;
    }
    cell.titileLabel.text = contentArra[indexPath.row];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 25;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    LKOrderEditTopView *topView = [[[NSBundle mainBundle] loadNibNamed:@"LKOrderEditTopView" owner:self options:nil] lastObject];
    topView.rightBtn.hidden = YES;
    NSString *title = [[self.titlesArray[section] allKeys] firstObject];
    [topView.leftBtn setTitle:title forState:UIControlStateNormal];
    [topView.leftBtn setImage:[UIImage imageNamed:@"322"] forState:UIControlStateNormal];
    if (section != 0) {
        [topView.leftBtn setImage:[UIImage imageNamed:@"323"] forState:UIControlStateNormal];
    }
    return topView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 43;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    WS(weakSelf)
    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor = [UIColor whiteColor];
    
    if (section != 0) {
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancelBtn setTitle:@"取消预约" forState:UIControlStateNormal];
        [cancelBtn setTitleColor:COLOR_HEX(0xFFA200) forState:UIControlStateNormal];
        cancelBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [footerView addSubview:cancelBtn];
        [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(footerView.mas_right).offset(-15);
            make.centerY.equalTo(footerView.mas_centerY);
            make.width.mas_equalTo(75);
        }];
        cancelBtn.layer.borderColor = COLOR_HEX(0xFFA200).CGColor;
        cancelBtn.layer.borderWidth = 1;
        [[cancelBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf.titlesArray removeObjectAtIndex:section];
            [self.tableView reloadData];
            [weakSelf cancelAppointmentProductWithId:weakSelf.idsArray[section]];
        }];
    }
    return footerView;
    
}

/**
 取消预约的产品
 */
-(void)cancelAppointmentProductWithId:(NSString *)Id{
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:Id,@"Id", nil];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:cancelAppointmentUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        
        [SVProgressHUD showInfoWithStatus:@"您已成功取消预约"];
        
    } failure:^(NSString * _Nullable errorMessage) {
//        [SVProgressHUD showInfoWithStatus:@"您已成功取消预约"];
    }];
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return section == 0 ? 12:43;
}

/**
 获取当前预约客户的会员的详细信息
 */
-(void)getCurrentCustomerInformation{
    NSDictionary *param;
    if (self.isOrderUpdate) {
        param = [NSDictionary dictionaryWithObjectsAndKeys:self.customerId,@"Id",@"1",@"PageIndex",@"20",@"MaxResultCount", nil];
    }else{
       param  = [NSDictionary dictionaryWithObjectsAndKeys:_model.customerId,@"Id",@"1",@"PageIndex",@"20",@"MaxResultCount", nil];
    }

//    NSDictionary *param = @{@"Id":_model.customerId,@"PageIndex":@"1",@"MaxResultCount":@"20"};
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:AppointmentUserInforUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject[@"result"];
        
        LKCustomerModel *model = [LKCustomerModel modelWithDictionary:dic];
        
        self.model = model;
        NSString *customerName = [NSString stringWithFormat:@"%@%@",@"客户名称：",_model.customerName];
        NSString *customerCode = [NSString stringWithFormat:@"%@%@",@"客户编号：",_model.customerCode];
        NSString *customerSex = [_model.customerGender  isEqual: @"0"] ?@"男":@"女";
        NSString *customerS = [NSString stringWithFormat:@"%@%@",@"性别：",customerSex];
        NSString *tel = [NSString stringWithFormat:@"%@%@",@"电话：",_model.tel];
        NSString *identCatory = [NSString stringWithFormat:@"%@%@",@"证件类型：",[NSString backTitleAccordingIdCatogaryType:[_model.identitfyCategory integerValue]]];
        NSString *sorce = [NSString stringWithFormat:@"%@%@",@"来源：",[NSString backTitleAccordingSorceType:[_model.source integerValue]]];
        NSString *vipLevel = [NSString stringWithFormat:@"%@%@",@"会员等级：",_model.customerLevelName];
        NSString *jifen = [NSString stringWithFormat:@"%@%@",@"积分：",_model.pointQuota];
        NSString *owener = [NSString stringWithFormat:@"%@%@",@"所属人：",[LKUserInforTool account].name];
        NSString *identId = [NSString stringWithFormat:@"%@%@",@"证件号码：",_model.identityId];
        [self.idsArray addObject:@" "];
        [self.titlesArray addObjectsFromArray:@[@{@" 会员信息":@[customerCode,vipLevel,customerName,customerS,tel,jifen,identCatory,identId,sorce,owener]}]];
        NSArray *itemsArra = dic[@"customerReservationDto"][@"item"];
        for (NSDictionary *dics in itemsArra) {
            NSString *productName = [NSString stringWithFormat:@"%@%@",@"产品名称：",dics[@"productKeyName"]];
            NSString *productCode = [NSString stringWithFormat:@"%@%@",@"产品编号：",dics[@"productKeyCode"]];
            NSString *productType = [NSString stringWithFormat:@"%@%@",@"产品类型：",dics[@"productTypeTest"]];
            NSString *producterm = [NSString stringWithFormat:@"%@%@（月）",@"产品期限：",dics[@"productTerm"]];
            NSString *duifufangshi = [NSString stringWithFormat:@"%@%@",@"兑付方式：",dics[@"payCategoryTest"]];
            NSString *yuyueedu = [NSString stringWithFormat:@"%@%@",@"预约额度：",dics[@"reservationAmount"]];
            NSString *yuyueshijian = [NSString stringWithFormat:@"%@%@",@"预约时间：",dics[@"reservationDateTest"]];
            NSString *shixiaoshijian = [NSString stringWithFormat:@"%@%@",@"失效时间：",dics[@"invalidTimeTest"]];
            NSString *ts = [self backIsReservationMemberCount:[dics[@"reservationMemberCount"] integerValue]];
            NSString *shifouzaitou = [NSString stringWithFormat:@"%@%@",@"产品名称：",ts];
            [self.titlesArray addObjectsFromArray:@[@{@" 预约产品栏":@[productName,productCode,productType,producterm,duifufangshi,yuyueedu,yuyueshijian,shixiaoshijian,shifouzaitou]}]];
            [self.idsArray addObject:dics[@"id"]];
        }
        
        [self.tableView reloadData];
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
    
/**
 是否在投资相似产品

 @param NSString 类型
 @return 值
 */
}
-(NSString *)backIsReservationMemberCount:(NSInteger)type{
    if (type == 0) {
        return @"是在投此资产产品";
    }
    return @"不在投此资产产品";
}
-(NSMutableArray *)titlesArray{
    if (!_titlesArray) {
//        _titlesArray = @[@{@" 会员信息":@[@"会员编号：",@"会员等级",@"姓名：",@"性别：",@"电话：",@"积分：",@"证件类型：",@"证件号码：",@"客户来源：",@"所属人："]},@{@" 预约产品栏":@[@"产品名称：",@"产品编号：",@"产品类型：",@"产品期限：",@"兑付方式：",@"预约额度：",@"预约时间：",@"失效时间：",@"是否在此投此资产产品"]}];
        _titlesArray = [[NSMutableArray alloc] init];
    }
    return _titlesArray;
}
-(NSMutableArray *)idsArray{
    if (!_idsArray) {
        _idsArray = [[NSMutableArray alloc] init];
    }
    return _idsArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
